import Cookies from 'js-cookie'

let storeExpires = 7; //默认缓存7天

//获取本地存储信息
let localUserMsg = null
let storeType = -1
if (!navigator.cookieEnabled && !window.localStorage) {
    window.console.error('无法获取Cookie或localStorage')
    window.alert('抱歉，您的浏览器禁用了Cookie，且不支持localStorage，请取消禁用浏览器Cookie，否则我们无法将无法记住你的信息，您将以游客的身份访问')
} else if (navigator.cookieEnabled) {
    storeType = 1
    if (Cookies.get('userMsg')) {
        localUserMsg = JSON.parse(Cookies.get('userMsg'));
    }
} else {
    storeType = 2
    if (window.localStorage.getItem('userMsg')) {
        localUserMsg = JSON.parse(window.localStorage.getItem('userMsg'))
    }
}

//state
//shape [user, admin]
const state = {
    userType: -1,
    userMsg: localUserMsg ? localUserMsg : [{}, {}],
    userStoreType: storeType,
    isLegal: false
}

//getters
const getters = {
    getUserType: (state) => {
        return state.userType
    },
    getUserMsg: (state) => {
        if (state.userType < 0) {
            return null
        } else {
            return state.userMsg[state.userType]
        }
    },
    getUserStoreType: (state) => {
        return state.userStoreType < 0 ? false : true;
    },
    getUserIsLegal: (state) => {
        return state.isLegal
    }
}

//actions
const actions = {}

//mutations
const mutations = {
    setUserType(state, uType) {
        state.userType = uType
    },
    setUserMsg(state, uMsg, logout = false) {
        if (state.userType >= 0) {
            if (Object.prototype.toString.call(uMsg) === '[object Object]') {
                uMsg = JSON.parse(JSON.stringify(uMsg))
                if (state.userType == 0) {
                    state.userMsg = [uMsg, state.userMsg[1]];
                } else {
                    state.userMsg = [state.userMsg[0], uMsg];
                }
                if (state.userStoreType == 1) {
                    let tempStore = Cookies.get('userMsg') ? JSON.parse(Cookies.get('userMsg')) : [{}, {}];
                    tempStore[state.userType] = uMsg
                    Cookies.set('userMsg', JSON.stringify(tempStore), { expires: storeExpires })
                } else {
                    let tempStore = window.localStorage.getItem('userMsg') ? JSON.parse(window.localStorage.getItem('userMsg')) : [{}, {}];
                    tempStore[state.userType] = uMsg
                    window.localStorage.setItem('userMsg', JSON.stringify(tempStore))
                }
                if (logout) {
                    state.isLegal = false;
                }
            } else {
                window.console.error('userMsg must be a object!');
            }
        }
    },
    setUserIsLegal(state, legal) {
        state.isLegal = legal
    }
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}